package com.example.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.enums.CodeEnum;
import com.example.demo.common.enums.DataEnum;
import com.example.demo.common.exception.BaseRuntimeException;
import com.example.demo.dao.UserTDao;
import com.example.demo.entity.UserT;
import com.example.demo.service.UserTService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * (UserT)表服务实现类
 *
 * @author makejava
 * @since 2024-11-06 15:23:06
 */
@Service("userTService")
public class UserTServiceImpl extends ServiceImpl<UserTDao, UserT> implements UserTService {

    @Override
    public UserT selectByUserName(String username) {
        LambdaQueryWrapper<UserT> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.
                eq(UserT::getUserName, username).
                eq(UserT::getDelFlag, DataEnum.DEL_FAG_VALID.getCode());
        return this.getOne(queryWrapper);
    }

    @Override
    public UserT checkToken(String token) {

        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 23:59:59");
        String nowDate = today.format(formatter);
        LambdaQueryWrapper<UserT> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(UserT::getToken, token)
                .eq(UserT::getDelFlag, DataEnum.DEL_FAG_VALID.getCode())
                .ge(UserT::getLoginTime, nowDate);
        UserT one = this.getOne(queryWrapper);
        if(ObjectUtils.isEmpty(one)){
            throw new BaseRuntimeException(CodeEnum.FAILTOKEN.getCode(), "token已过期");
        }
        return one;
    }
}

